package com.sunyard.manage.util.zhonghang;

import lombok.extern.slf4j.Slf4j;
import sun.misc.BASE64Decoder;

import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;

@Slf4j
public class Des3 {
	private static String Algorithm = "DESede";//加密算法的名称
	private static Cipher c;//密码器
	private static byte[] cipherByte;
	private static SecretKey deskey;//密钥
	private static String keyString = "5dI2LJtk/z/gIEa0XsN66lASdvNHBmUV";//获得密钥的参数(请保持加密解密~密钥的相同,具体请自行修改)

	//对base64编码的string解码成byte数组
	public byte[] deBase64(String parm) throws IOException {
		BASE64Decoder dec=new BASE64Decoder();
		byte[] dnParm = dec.decodeBuffer(parm);
		return dnParm;
	}
	//把密钥参数转为byte数组
	public byte[] dBase64(String parm) throws IOException {
		BASE64Decoder dec=new BASE64Decoder();
		byte[] dnParm = dec.decodeBuffer(parm);
		return dnParm;
	}

	public static String createDecryptor(byte[] buff) throws
            NoSuchPaddingException, NoSuchAlgorithmException,
            UnsupportedEncodingException {
		try {
			c.init(Cipher.DECRYPT_MODE, deskey);//初始化密码器，用密钥deskey,进入解密模式
			cipherByte = c.doFinal(buff);
		}
		catch(InvalidKeyException ex){
			ex.printStackTrace();
		}
		catch(javax.crypto.BadPaddingException ex){
			ex.printStackTrace();
		}
		catch(javax.crypto.IllegalBlockSizeException ex){
			ex.printStackTrace();
		}
		return (new String(cipherByte,"UTF-8"));
	}



	public void getKey(String key) throws IOException, InvalidKeyException,
            InvalidKeySpecException {
		byte[] dKey = dBase64(key);
		try {
			deskey=new javax.crypto.spec.SecretKeySpec(dKey,Algorithm);
			c = Cipher.getInstance(Algorithm);
		}
		catch (NoSuchPaddingException ex) {
			ex.printStackTrace();
		}
		catch (NoSuchAlgorithmException ex) {
			ex.printStackTrace();
		}
	}

	public static String decryptor(String ticket){
		String dStr = "";
		try {
			Des3 des = new Des3();
			des.getKey(keyString);
			//要解码的字符
			byte[] dBy = des.deBase64(ticket);
			dStr = Des3.createDecryptor(dBy);
		} catch (Exception e) {
			log.error("解密ticket失败:{}",e.getMessage());
			e.printStackTrace();
		}
		return dStr;
	}

	public static void main(String args[]) {
		String decryptor = decryptor("xBjIIvVBfCo=");
		System.out.println("解码为："+decryptor);
	}
	
	public static String getStr(String str)
	{
		Des3 des = new Des3();
		String dStr="";
		try {
			des.getKey(keyString);
			byte[] dBy = des.deBase64(str);
			dStr = Des3.createDecryptor(dBy);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return dStr;
	}
}